import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_yres/model/jiayouList_model.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/pages/jiayouzhan/jyz_detail_page.dart';
import 'package:jlocation/jlocation.dart';

class JYZListPage extends StatefulWidget {
  @override
  _JYZListPageState createState() => _JYZListPageState();
}

class _JYZListPageState extends State<JYZListPage> {
  double _listHeight = ScreenUtil.getInstance().setHeight(210); //单个列表高度
  EasyRefreshController _controller = new EasyRefreshController();
  int jyz_page = 1;
  List<JYZModelData> jyzListData = []; //加油站数组
  
  double lat, lng;
  
  //加油站参数
  List<DropdownMenuItem> jyz_distanceItemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1000',
        child: new Text(
          '1千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '3000',
        child: new Text(
          '3千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '5000',
        child: new Text(
          '5千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '10000',
        child: new Text(
          '10千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  var jyz_selectDistanceItemValue = '10000';
 var jyz_selectoilNoItemValue;
var jyz_selectCondItemValue;
var jyz_selectGasTypeItemValue;
  List<DropdownMenuItem> jyz_oilNotemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '92',
        child: new Text(
          '#92',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '95',
        child: new Text(
          '#95',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '98',
        child: new Text(
          '#98',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '0',
        child: new Text(
          '#0',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

 

  List<DropdownMenuItem> jyz_condtemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '油价升序',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '距离升序',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    return items;
  }

  

  List<DropdownMenuItem> jyz_gasTypetemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '中石油',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '中石化',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '3',
        child: new Text(
          '壳牌',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '4',
        child: new Text(
          '其他',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('加油'),
      ),
      body: new Stack(
        children: <Widget>[
          Container(
              margin: EdgeInsets.fromLTRB(0, ScreenUtil.getInstance().setHeight(40), 0, 0),
              child: EasyRefresh(
                  controller: _controller,
                  header: MaterialHeader(),
                      footer: MaterialFooter(),
                      enableControlFinishLoad: true,
                      enableControlFinishRefresh: true,
                  child: CustomScrollView(slivers: <Widget>[
                    SliverToBoxAdapter(child: Container()),
                    SliverFixedExtentList(
                        delegate: _buildTypeList(), itemExtent: _listHeight),
                    SliverToBoxAdapter(
                      child: Container(),
                    ),
                  ]),
                  onRefresh: () async {
                    _refreshList();
                  },
                  onLoad: () async {
                    jyz_page++;
                    getJYStationList(
                        jyz_selectGasTypeItemValue,
                        jyz_selectDistanceItemValue,
                        jyz_selectoilNoItemValue,
                        jyz_selectCondItemValue);
                  })),
          _buildPopHeader()
        ],
      ),
    );
  }

  SliverChildDelegate _buildTypeList() {
    return SliverChildBuilderDelegate(_buildListItem,
        childCount: jyzListData.length);
  }

  _buildPopHeader() {
    //条件筛选头部
    var jyz_header = Container(
      height: ScreenUtil.getInstance().setHeight(40),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '距离',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectDistanceItemValue,
                    items: jyz_distanceItemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectDistanceItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '油号编码',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectoilNoItemValue,
                    items: jyz_oilNotemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectoilNoItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '排序',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectCondItemValue,
                    items: jyz_condtemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectCondItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '加油站类型',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectGasTypeItemValue,
                    items: jyz_gasTypetemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectGasTypeItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              ))
        ],
      ),
    );
    return jyz_header;
  }

/***************************加油站数据列表**************************/
  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
         JYZModelData model =  jyzListData[index];
          // var gasIds=model.gasid;
            Navigator.push(context, MaterialPageRoute(    //导航打开新视图
              builder: (context) => JYZDetailPage(model:model) //打开第二个页面，并传值，传递值的名称是model
            ));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    //左图
    var image = new Image(
        image: NetworkImage(jyzListData[index].gaslogosmall),
        width: ScreenUtil.getInstance().setHeight(150),
        height: ScreenUtil.getInstance().setHeight(150),
        fit: BoxFit.fill);
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    //右内容
    var title = Text(
      jyzListData[index].gasname,
      style: TextStyle(color: Colors.black, fontSize: 16.0),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            text: jyzListData[index].priceyfq,
            style: TextStyle(fontSize: 18.0)),
        TextSpan(
            text: '/升/' + jyzListData[index].oilname,
            style: TextStyle(fontSize: 12.0)),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var distance = RichText(
      text: TextSpan(style: TextStyle(fontSize: 13.0), children: [
        TextSpan(
            text: jyzListData[index].distance,
            style: TextStyle(color: Colors.grey)),
        TextSpan(text: '导航', style: TextStyle(color: Colors.orange)),
      ]),
    );
    var address = Text(
      jyzListData[index].provincename +
          jyzListData[index].cityname +
          jyzListData[index].countyname +
          jyzListData[index].gasaddress,
      style: TextStyle(color: Colors.grey, fontSize: 13.0),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 8),
        Row(
          children: <Widget>[_pd(price, l: 10, t: 0, r: 10, b: 8), distance],
        ),
        _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  @override
  void initState() {
    _getLoginMsg();
    super.initState();

  }

  @override
  void dispose() {
    // AMapLocationClient.shutdown();
    super.dispose();
  }

  void _refreshList() {
    jyz_page = 1;
    getJYStationList(jyz_selectGasTypeItemValue, jyz_selectDistanceItemValue,
        jyz_selectoilNoItemValue, jyz_selectCondItemValue);
  }

/*获取列表数据*/
  getJYStationList(gasType, distinct, oilNo, cond) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    //加油站

        FormData data;
    if (lat == null) {
      data = new FormData.fromMap({
        'token': preferences.get("token"),
        'gasType': gasType,
        'phone': preferences.get("name"),
        'distinct': distinct,
        'page': jyz_page,
        'per': '8',
        'oilNo': oilNo, //油号编码
        'cond': cond
      });
    } else {
      data = new FormData.fromMap({
        'token': preferences.get("token"),
        'gasType': gasType,
        'phone': preferences.get("name"),
        'lng_lat':lng.toString()+","+lat.toString(),
        'distinct': distinct,
        'page': jyz_page,
        'per': '8',
        'oilNo': oilNo, //油号编码
        'cond': cond
      });
    }

    Response<String> response =
        await HttpUtil().post(Api.kGetGasoilURL, data: data);
    Map userMap = json.decode(response.data);
    JYZModelEntity jyzEntity = new JYZModelEntity.fromJson(userMap);
    if (jyzEntity.code == 0) {
      if (mounted) {
        setState(() {
          if (jyz_page == 1) {
            jyzListData.clear();
            jyzListData = jyzEntity.data;
          } else {
            jyzListData.addAll(jyzEntity.data);
          }
        });
      }
    }
  }

  //获取用户登录信息
  void _getLoginMsg() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    var token = preferences.get("token");
    if (token == null || token == '') {
      Navigator.of(context).pushNamed("login");
    } else {
      getLocation();
    }
  }

   getLocation() {
    var loc = new Jlocation();
    loc.onLocationChanged().listen((loc) {
      // Navigator.of(context).pop(1);
      setState(() {
        if (!mounted) return;
        lat = loc.latitude;
        lng = loc.longitude;
        jyz_page=1;
        getJYStationList(
            jyz_selectGasTypeItemValue,
            jyz_selectDistanceItemValue,
            jyz_selectoilNoItemValue,
            jyz_selectCondItemValue);
      });
    });
  }
}
